package com.xiaour.spring.boot.jms;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import java.io.ByteArrayOutputStream;

@Component
public class MyJmsListener {

    @JmsListener(destination = "my_queue")
    public void receiveMessage(Message message) {
        try {
            if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = bytesMessage.readBytes(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                String convertedMessage = new String(outputStream.toByteArray());
                System.out.println("Received BytesMessage, converted to String: " + convertedMessage);
            } else if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println("Received TextMessage: " + textMessage.getText());
            } else {
                System.out.println("Received unknown message type: " + message.getClass());
            }
        } catch (JMSException e) {
            System.err.println("Failed to process message: " + e.getMessage());
        }
    }
}

